package juc.juccore.future;

import java.util.concurrent.*;

/*演示get的超时方法,演示cancel传入ture和false的区别
 */
public class Timeout {
    private static final Ad DEFAULT_AD = new Ad("默认的广告");
    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);

    static class Ad {
        String name;

        public Ad(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Ad{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

    static class FetchAdTask implements Callable {

        @Override
        public Object call() throws Exception {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                System.out.println("sleep期间被中断了");
                return new Ad("被中断时候的默认广告");
            }
            return new Ad("旅游订票哪家强?找??");
        }
    }


    public void printAd() {
        Future<Ad> f = EXECUTOR_SERVICE.submit(new FetchAdTask());
        Ad ad;
        try {
            ad = f.get(1, TimeUnit.SECONDS);
        } catch (ExecutionException e) {
            ad = new Ad("异常时候的默认广告");

        } catch (InterruptedException e) {
            ad = new Ad("被中断时候的默认广告");
        } catch (TimeoutException e) {
            ad = new Ad("超时时候的默认广告");
            System.out.println("超时,未获取到广告");
            boolean cancel = f.cancel(false);
            System.out.println("cancel的结果" + cancel);
        }
        EXECUTOR_SERVICE.shutdown();
        System.out.println(ad);
    }

    public static void main(String[] args) {
        Timeout timeout = new Timeout();
        timeout.printAd();
    }
}
